package services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;

import com.aton.db.SessionFactory;

import models.Role;
import models.RoleUser;
import models.mappers.OperatorMapper;
import models.mappers.RoleUserMapper;

public class RoleUserService {
	/**
	 * 获取角色列表
	 *
	 * @Title: getRole 
	 * @return
	 * @return: List<Role>
	 */
	public static List<Role> getRole() {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			RoleUserMapper mapper = ss.getMapper(RoleUserMapper.class);
            return mapper.getRole();
        } finally {
            ss.close();
        }
	}
	/**
	 * 获取角色用户
	 *
	 * @Title: getRoleOperator 
	 * @param roleid
	 * @return
	 * @return: List<String>
	 */
	public static List<String> getRoleOperator(String roleid) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			RoleUserMapper mapper = ss.getMapper(RoleUserMapper.class);
            return mapper.getRoleOperator(roleid);
        } finally {
            ss.close();
        }
	}
	/**
	 * 保存
	 *
	 * @Title: saveRoleUser 
	 * @param roleid
	 * @param operList
	 * @return
	 * @return: boolean
	 */
	public static boolean saveRoleUser(String roleid, Set<String> operList) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		List<RoleUser> listMap=new ArrayList<RoleUser>();
		Map<String,List<RoleUser>> smap=new HashMap<String,List<RoleUser>>();
		if(operList!=null&&operList.size()>0){
			Iterator it = operList.iterator();
			while(it.hasNext()){
				RoleUser roleUser=new RoleUser(roleid,it.next().toString());
				listMap.add(roleUser);
			}
		}
		else{
			listMap=null;
		}
		smap.put("operids", listMap);
		try {
			RoleUserMapper mapper = ss.getMapper(RoleUserMapper.class);
			mapper.deleteRoleUser(roleid);
			if(listMap!=null){
				 mapper.saveRoleUser(smap);
			}
            ss.commit();
        }catch(Exception e){
        	ss.rollback();
        	e.printStackTrace();
        	return false;
        }finally {
            ss.close();
        }
		return true;
	}
}
